package com.automannn.tomcat.practice.springWeb.springSecurity;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.FilterChainProxy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;

/**
 * @author chenkh
 * @time 2021/10/18 10:56
 */
@Component
@EnableWebSecurity(debug = true)
public class SecurityFilterChainConfig {

    @Bean
    /*xxx: 由于 SpringSecurity的 FilterChainProxy 默认情况下，不是在原生 spring容器环境初始化的
       ，因此 当前定义的 过滤链，不能自动应用 spring的默认过滤链中*/
    public SecurityFilterChain securityFilterChain1(){
        RequestMatcher requestMatcher = new RequestMatcher() {
            @Override
            public boolean matches(HttpServletRequest httpServletRequest) {
                return true;
            }
        };
        Filter filter = new Filter() {
            @Override
            public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
                System.out.println("自定义的过滤器，在springSecurityFilterChain中生效.");
                filterChain.doFilter(servletRequest,servletResponse);
            }
        };
       SecurityFilterChain securityFilterChain = new DefaultSecurityFilterChain(requestMatcher,filter);
       return securityFilterChain;
    };

    /*xxx: springSecurity 通过 WebSecurityConfiguration 配置 FilterChainProxy,
       并且，该过滤器代理 是通过 webSecurity.build()方法获得的。 */
    /*xxx: WebSecurity 是一个工具类，它可以将当前上下文配置的 SecurityConfigurer进行整合，最后构造出 过滤链列表 ，
       并将这些过滤链 应用于 默认的 FilterChainProxy中 */
//    @Bean
//    public FilterChainProxy springSecurityFilterChain(List<SecurityFilterChain> filterChains){
//        FilterChainProxy filterChain = new FilterChainProxy(filterChains);
//        return filterChain;
//    }
}
